package com.boot.mall.order.interceptor;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.common.constant.AuthConstant;
import com.boot.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> thread = new ThreadLocal<>();

    /**
     * 判断session当中是否含有用户信息，当session当中没有用户信息的时候跳转登录页
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行远程调用的方法
        // 获取请求的路径
        String uri = request.getRequestURI();
        // 匹配当前路径，直接放行
        boolean matchOrder = new AntPathMatcher().match("/order/order/status/**", uri);
        if (matchOrder){
            return true;
        }
        System.out.println(uri);
        boolean matchAlipay = new AntPathMatcher().match("/alipay/**", uri);
        if (matchAlipay){
            return true;
        }

        MemberResponseVo attribute = (MemberResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (attribute != null){
            // 将登录的用户信息放入当前线程对象中
            thread.set(attribute);
            return true;
        }else {
            request.getSession();
            // 没有用户登录，跳转登录页
            response.sendRedirect("http://auth.guli.com/login.html");
            return false;   //拦截
        }
    }
}
